package com.zw.cc.shiro;

import com.zw.cc.model.UserLoginEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

/**
 * Created by zwz
 * date 2016/12/26
 * project com.zw.cc.shiro
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * 授权
     * 权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户
        UserLoginEntity token = (UserLoginEntity) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //角色code集合
//        List<String> roles = userService.queryUserRole(token.getId());
//        List<String> permiss = userService.queryUserRole(token.getId());
//        设置角色和权限
//        simpleAuthorInfo.addRoles(roles);
//        simpleAuthorInfo.addStringPermissions(permiss);
        return simpleAuthorInfo;
    }

    /**
     * 认证
     * 登陆
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserLoginEntity user = new UserLoginEntity();
        user.setPassword(String.valueOf(token.getPassword()));
        user.setAccount(String.valueOf(token.getUsername()));
        // 查询数据库
        //user = userService.validUser(user);
        if(null == user) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(), getName());
    }
}
